import React from "react";
import "./BookDetails.css";
import $ from "jquery";
import { Comment, List, Avatar, Rate, Modal, Button, Input } from "antd";
import { setStorage, getStorage } from "../../utils/utils";
const { TextArea } = Input;


class BookDetails extends React.Component {
  constructor() {
    super();
    this.state = {
      loading: false,
      bookDetails: {},
      bookComments: [],
      huifuComments: {},
      now: '',
      visible: false,
      commentsValue: '',
      score: null,
    };
  }

  componentDidMount() {
    let bookId = this.props.history.location.state
      ? this.props.history.location.state.id
      : getStorage("bookId");
    console.log(bookId)
    if (bookId) {
      setStorage("bookId", bookId);
    }
    this.getBookDetails(bookId);
    this.getBookComments(bookId);
    if (getStorage('user')) {
      this.getPersonDetails()
    }
  }

  getPersonDetails = () => {
    this.axios({
      url: '/index/getPersonDetails',
      method: 'post',
      data: { userId: getStorage('user').Userid },
    }).then(data => {
      if (data.data.code === 200) {
        setStorage('user', data.data.data[0])
        this.setState({
          user: data.data.data[0]
        })
      }
    })
  }

  zhanai() {
    if ($("#jianjie").hasClass("jianjie")) {
      $("#jianjie").removeClass("jianjie");
      $("#zhankai1").text("收起");
      $("#fangxiang").css({
        transform: "rotate(180deg)",
      });
    } else {
      $("#jianjie").addClass("jianjie");
      $("#zhankai1").text("展开");
      $("#fangxiang").css({
        transform: "rotate(0deg)",
      });
    }
  }

  //   获取书籍详情
  getBookDetails(bookId) {
    this.axios({
      url: "/index/getBookDetails",
      method: "post",
      data: { bookId: bookId },
    }).then((data) => {
      let newObj = data.data.data[0];
      console.log(newObj);
      if (newObj.bookIntroduce.length > 167) {
        newObj.isZhankai = true;
      } else {
        newObj.isZhankai = false;
      }
      if (newObj.bookWords > 100000) {
        newObj.bookWords = (newObj.bookWords / 10000).toFixed(1) + "万";
      }
      if (newObj.fansNum > 100000) {
        newObj.fansNum = (newObj.fansNum / 10000).toFixed(1) + "万";
      }
      if (newObj.likeNum > 100000) {
        newObj.likeNum = (newObj.likeNum / 10000).toFixed(1) + "万";
      }
      if (newObj.commentsPeopleNum > 100000) {
        newObj.commentsPeopleNum =
          (newObj.commentsPeopleNum / 10000).toFixed(1) + "w+";
      }
      if (newObj.commentsPostNum > 100000) {
        newObj.commentsPostNum =
          (newObj.commentsPostNum / 10000).toFixed(1) + "w+";
      }

      if (newObj.bookPrice === 0) newObj.bookPrice = "免费";
      else if (newObj.bookPrice < 50)
        newObj.bookPrice = newObj.bookPrice + "阅币/千字";
      else newObj.bookPrice = newObj.bookPrice + "阅币";

      if (newObj.bookOriginalPrice === null) newObj.bookOriginalPrice = "";
      else if (newObj.bookOriginalPrice < 50) {
        newObj.bookOriginalPrice = newObj.bookOriginalPrice + "阅币/千字";
      } else {
        newObj.bookOriginalPrice = newObj.bookOriginalPrice + "阅币";
      }

      this.setState({
        bookDetails: newObj,
        loading: true,
      });
    });
  }

  //   获取书籍评论信息
  getBookComments(bookId) {
    this.axios({
      url: "/index/getBookComments",
      method: "post",
      data: { bookId: bookId },
    }).then((data) => {
      console.log(data.data.data);
      let newArr = [];
      let obj = {};
      data.data.data.forEach((item, i) => {
        for (let i = 0; i < item.giveLikeAccountId.length; i++) {
          item.giveLikeAccountId[i] = parseInt(item.giveLikeAccountId[i])
        }
        obj = {
          actions: [
            <div>
              <div className="dianzanpinglun">
                <p onClick={() => this.giveLike(item)}>
                  {
                    getStorage('user') ? (
                      <>
                        {
                          item.giveLikeAccountId.indexOf(getStorage('user').Userid) !== -1 ? (
                            <span style={{ color: '#f26552' }} className="iconfont icon-ai45"></span>
                          ) : (
                            <span className="iconfont icon-ai45"></span>
                          )
                        }
                      </>
                    ) : (
                      <span className="iconfont icon-ai45"></span>
                    )
                  }
                  <span>{item.commentsLikeNum}</span>
                </p>
                <p onClick={() => this.xianshi(i, true)}>
                  <span className="iconfont icon-pinglun"></span>
                  <span>回复</span>
                </p>
              </div>
              <div>

              </div>
              <div className='commentText'>
                <TextArea className='commentContent' rows={4} />
                <Button type="primary" size='small' onClick={() => this.xianshi(i, false)}>
                  发送
                </Button>
              </div>
            </div>,
          ],
          author: (
            <div className="topRightList">
              <div>
                <span className="userName">{item.UserName}</span>
                <span className="level">LV{item.Level}</span>
                <span className="VIP">VIP</span>
              </div>
              <div className="Date">{item.commentsTime}</div>
              {
                item.commentsScore !== null ? (
                  <div className="bookScore">
                    <Rate disabled defaultValue={item.commentsScore} />
                  </div>
                ) : (
                  <></>
                )
              }

            </div>
          ),
          avatar: (
            <Avatar
              className="headImg"
              src={"http://localhost:8888" + item.HeadImg}
              alt={item.UserName}
            />
          ),
          content: (
            <p className="detailContext">
              <span className="shupin">书评</span>
              {item.commentsContext}
            </p>
          ),
        };
        newArr.push(obj);
      });
      this.setState({
        bookComments: newArr,
        loading: true,
      });
    });
  }

  // 去到阅读书籍页面
  gotoReadBook() {
    this.props.history.push({
      pathname: "/ReadBook",
      state: { bookInformation: this.state.bookDetails },
    })
  }

  xianshi(index, state) {
    if (state) {
      for (let i = 0; i < $('.commentText').length; i++) {
        if (i === index) {
          $('.commentText')[i].style.display = 'block'
        } else {
          $('.commentText')[i].style.display = 'none'
        }
      }
    } else {
      let content = $('.commentContent')[index].innerHTML
      for (let i = 0; i < $('.commentText').length; i++) {
        $('.commentText')[i].style.display = 'none'
      }
      let obj = {};
      obj = {
        actions: [

        ],
        author: (
          <div className="topRightList">
            <div>
              <span className="userName">{getStorage('user').UserName}</span>
              <span className="level">LV{getStorage('user').Level}</span>
              <span className="VIP">VIP</span>
            </div>
          </div>
        ),
        avatar: (
          <Avatar
            className="headImg"
            src={"http://localhost:8888" + getStorage('user').HeadImg}
            alt={getStorage('user').UserName}
          />
        ),
        content: (
          <p className="detailContext">
            <span className="shupin">书评</span>
            {content}
          </p>
        ),
      };
      this.setState({
        huifuComments: obj,
        now: index,
      })
    }

  }

  // 点赞
  giveLike(item) {
    if (getStorage('user')) {
      let num, newArr = item.giveLikeAccountId
      for (let i = 0; i < newArr.length; i++) {
        newArr[i] = parseInt(newArr[i])
      }
      console.log(newArr)
      if (newArr.indexOf(getStorage('user').Userid) !== -1) {
        num = -1
        console.log(newArr.indexOf(getStorage('user').Userid))
        newArr.splice(newArr.indexOf(getStorage('user').Userid), 1)
      } else {
        num = 1
        newArr.push(getStorage('user').Userid)
      }
      console.log(newArr)
      this.axios({
        url: '/giveLike',
        method: 'post',
        data: { commentsId: item.id, num: num, newgiveLikeAccountId: newArr }
      }).then(data => {
        this.getBookComments(getStorage("bookId"))
      })
    } else {
      this.countDown()
    }
  }

  publishedComment() {
    if (getStorage('user')) {
      this.setState({ visible: true });
    } else {
      this.countDown()
    }
  }

  // 未登录提示
  countDown() {
    let secondsToGo = 3;
    const modal = Modal.error({
      title: '当前未登录，请登陆后再执行此操作',
      content: `在${secondsToGo}秒之后自动跳转到登录界面`,
    });
    const timer = setInterval(() => {
      secondsToGo -= 1;
      modal.update({
        content: `在${secondsToGo}秒之后自动跳转到登录界面`,
      });
    }, 1000);
    setTimeout(() => {
      clearInterval(timer);
      modal.destroy();
      this.props.history.push('/Login')
    }, secondsToGo * 1000);
  }

  // 关闭发表评论modal
  addComment = () => {
    this.axios({
      url: '/addComments',
      method: 'post',
      data: {
        commentsBookId: getStorage('bookId'),
        commentsAuthorId: getStorage('user').Userid,
        commentsContext: this.state.commentsValue,
        score: this.state.score,
      }
    }).then(data => {
      this.getBookComments(getStorage("bookId"))
    })
    this.setState({
      visible: false,
      commentsValue: '',
    });
  };
  handleCancel = () => {
    this.setState({
      visible: false,
      commentsValue: '',
    });
  };

  // 评分
  giveScore(value) {
    this.setState({
      score: value,
    });
  }

  // 输入评论
  onChange(e) {
    this.setState({
      commentsValue: e.target.value
    })
  };

  // 添加到书架
  addBookCase() {
    if (getStorage('user')) {
      let BookcaseArr = this.state.user.bookcase.split(',')
      let newCase = []
      BookcaseArr.forEach(item => {
        newCase.push(parseInt(item))
      })
      newCase.push(getStorage('bookId'))
      let bookcase = newCase.join(',')
      this.axios({
        url: '/addBookCase',
        method: 'post',
        data: { userid: getStorage('user').Userid, bookcase: bookcase },
      }).then(data => {
        if (data.data.code === 200) {
          this.getPersonDetails()
        }
        console.log(data)
      })
    }
    else {
      this.countDown()
    }

  }

  // 添加书架
  addBookcaseBtn() {
    if (getStorage('user')) {
      if (getStorage('user').bookcase === null) {
        console.log(111)
      } else {
        let Bookcase = getStorage('user').bookcase.split(',')
        let newCase = []
        Bookcase.forEach(item => {
          newCase.push(parseInt(item))
        })
        if (newCase.indexOf(getStorage('bookId')) !== -1) {
          return (
            <Button type="primary" disabled>已添加</Button>
          )
        } else {
          return (
            <Button type="primary" onClick={() => this.addBookCase()}>添加到书架</Button>
          )
        }
      }

    }
    else {
      return (
        <Button type="primary" onClick={() => this.addBookCase()}>添加到书架</Button>
      )
    }

  }

  render() {
    if (this.state.loading) {
      return (
        <div>
          <div className="bookShow">
            <div className="leftShow">
              <img
                alt=""
                src={"http://localhost:8888" + this.state.bookDetails.bookImg}
              ></img>
            </div>
            <div className="rightShow">
              <div className="topRight">
                <div className="bookTitle">
                  <p>{this.state.bookDetails.bookName}</p>
                  <p>{this.state.bookDetails.bookScore}</p>
                </div>
                <div>
                  <p>
                    <span>作者：{this.state.bookDetails.authorName}</span>
                    <span>字数：{this.state.bookDetails.bookWords}字</span>
                    <span>粉丝数：{this.state.bookDetails.fansNum}</span>
                    <span>点赞数：{this.state.bookDetails.likeNum}</span>
                  </p>
                  <p>{this.state.bookDetails.scoresNum}人评分</p>
                </div>
              </div>
              <div className="middleRight">
                <div>
                  <div className="price">
                    <p>价格：{this.state.bookDetails.bookPrice}</p>
                    {this.state.bookDetails.bookOriginalPrice !== "" ? (
                      <p className="yuanjia">
                        原价：{this.state.bookDetails.bookOriginalPrice}
                      </p>
                    ) : (
                      <></>
                    )}
                  </div>
                  <div>
                    {this.state.bookDetails.bookPriceType === "普通" && (
                      <div>
                        <button className="free" onClick={() => this.gotoReadBook()}>免费试读</button>
                        <button className="buy">购买</button>
                      </div>
                    )}
                    {this.state.bookDetails.bookPriceType === "免费" && (
                      <div>
                        <button className="free" onClick={() => this.gotoReadBook()}>免费阅读</button>
                      </div>
                    )}
                    {this.state.bookDetails.bookPriceType === "特价" && (
                      <div>
                        {this.state.bookDetails.discount ? (
                          <div>
                            <button className="free" onClick={() => this.gotoReadBook()}>免费试读</button>
                            <button className="buy">
                              {this.state.bookDetails.discount}折购买
                          </button>
                          </div>
                        ) : (
                          <div>
                            <button className="free" onClick={() => this.gotoReadBook()}>免费试读</button>
                            <button className="buy">购买</button>
                          </div>
                        )}
                      </div>
                    )}
                    {this.state.bookDetails.bookPriceType === "VIP" && (
                      <div>
                        {this.state.bookDetails.discount ? (
                          <div>
                            <button className="free" onClick={() => this.gotoReadBook()}>免费试读</button>
                            <button className="buy">
                              {this.state.bookDetails.discount}折购买
                          </button>
                          </div>
                        ) : (
                          <div>
                            <button className="free" onClick={() => this.gotoReadBook()}>免费试读</button>
                            <button className="buy">购买</button>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>
                {this.addBookcaseBtn()}
              </div>
              <div className="bottomRight clear">
                <p id="jianjie" className="jianjie">
                  {this.state.bookDetails.bookIntroduce}
                </p>
                {this.state.bookDetails.isZhankai ? (
                  <div className="zhankai" onClick={() => this.zhanai()}>
                    <span id="zhankai1">展开</span>
                    <span
                      id="fangxiang"
                      className="iconfont icon-zhankai"
                    ></span>
                  </div>
                ) : (
                  <div></div>
                )}
              </div>
            </div>
          </div>
          <div className="bookComments">
            <div className="topComment">
              <div>
                <span>书友评论</span> <span className="line"> | </span>
                <span>共{this.state.bookDetails.commentsPeopleNum}人 , </span>
                <span> {this.state.bookDetails.commentsPostNum}条</span>
              </div>
              <div className="discuss" onClick={() => this.publishedComment()}>
                <span className="iconfont icon-bi"></span>我来说两句
              </div>
            </div>
            <div className="commentList">
              <List
                className="comment-list"
                itemLayout="horizontal"
                dataSource={this.state.bookComments}
                renderItem={(item, i) => (
                  <li>
                    <Comment
                      actions={item.actions}
                      author={item.author}
                      avatar={item.avatar}
                      content={item.content}
                      datetime={item.datetime}
                    />
                    {
                      i === this.state.now ? (<Comment style={{ marginLeft: '65px' }}
                        author={this.state.huifuComments.author}
                        avatar={this.state.huifuComments.avatar}
                        content={this.state.huifuComments.content}
                      />) : (<></>)
                    }

                  </li>
                )}
              />
            </div>
          </div>
          <Modal
            visible={this.state.visible}
            title="发表评论"
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            footer={[
              <Button key="back" onClick={() => this.handleCancel()}>
                取消
            </Button>,
              <Button key="submit" type="primary" onClick={() => this.addComment()}>
                发表评论
            </Button>,
            ]}
          >
            <div className='getScore'>
              <p>请对本书籍进行评分：</p>
              <Rate allowHalf onChange={(value) => this.giveScore(value)} />
            </div>

            <div className='publishComments'>
              {
                getStorage('user') ? (
                  <img alt='' src={'http://localhost:8888' + getStorage('user').HeadImg} />
                ) : (
                  <></>
                )
              }

              <TextArea value={this.state.commentsValue} allowClear showCount maxLength={100} onChange={(e) => this.onChange(e)} />
            </div>
          </Modal>
        </div>
      );
    } else {
      return <div></div>;
    }
  }
}
export default BookDetails;
